package com.hmall.search.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.hmall.common.dto.FiltersDto;
import com.hmall.common.dto.ItemDoc;
import com.hmall.common.dto.PageDTO;
import com.hmall.common.pojo.Item;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.lucene.search.function.CombineFunction;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;

/*
 *   Description SearchService
 *   @author zhangyan
 *   @time   2024/11/18
 */
@Service
@Slf4j
public class SearchService {
    @Autowired
    private RestHighLevelClient client;

    public PageDTO<Item> searchByCondition(FiltersDto filtersDto) {

        //创建查询请求对象
        SearchRequest request = new SearchRequest("item");
        //构建查询条件采用bool 查询
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        if (ObjectUtil.isEmpty(filtersDto.getKey()) || filtersDto.getKey().equals("")) {
            //查询所有
            boolQueryBuilder.must(QueryBuilders.matchAllQuery());
        } else {
            //根据名称查询
            boolQueryBuilder.must(QueryBuilders.matchQuery("name", filtersDto.getKey()));
        }
        //精确分类查询
        if (ObjectUtil.isNotEmpty(filtersDto.getCategory())) {

            boolQueryBuilder.filter(QueryBuilders.termQuery("category", filtersDto.getCategory()));
        }
        //精确品牌查询
        if (ObjectUtil.isNotEmpty(filtersDto.getBrand())) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("brand", filtersDto.getBrand()));
        }
        //价格区间查询
        if (ObjectUtil.isNotEmpty(filtersDto.getMinPrice())){
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(filtersDto.getMinPrice()));
        }
        if (ObjectUtil.isNotEmpty(filtersDto.getMaxPrice())){
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").lte(filtersDto.getMaxPrice()));
        }

        //算分函数查询
        FunctionScoreQueryBuilder scoreQueryBuilder = QueryBuilders.functionScoreQuery(
                boolQueryBuilder,
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                QueryBuilders.termQuery("isAD", true),
                                ScoreFunctionBuilders.weightFactorFunction(10)
                        )
                }
        );
        //设置boost模式
        scoreQueryBuilder.boostMode(CombineFunction.SUM);

        //设置查询条件
        request.source().query(scoreQueryBuilder);
        //分页
        int page = (filtersDto.getPage() - 1) * filtersDto.getSize();
        request.source().from(page).size(filtersDto.getSize());
        //排序
        String sortBy = filtersDto.getSortBy();
        if ("default".equals(sortBy) || "sold" .equals(sortBy)){
            request.source().sort("sold", SortOrder.DESC);
        }else{
            request.source().sort("price", SortOrder.DESC);
        }
        //搜索词高亮
        request.source().highlighter(new HighlightBuilder()
                .field("name")
                .requireFieldMatch(false)

        );
        ArrayList<Item> items = new ArrayList<>();
        //调用es
        try {
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            SearchHits responseHits = response.getHits();//第一层
            long total = responseHits.getTotalHits().value;//总记录数
            SearchHit[] hits = responseHits.getHits();
            if (hits != null && hits.length > 0){
                for (SearchHit hit : hits) {
                    String sourceAsString = hit.getSourceAsString();
                    ItemDoc itemDoc = JSONUtil.toBean(sourceAsString, ItemDoc.class);
                    Item item = BeanUtil.toBean(itemDoc, Item.class);

                     // 处理高亮结果
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                HighlightField nameHighlight = highlightFields.get("name");
                if (nameHighlight != null) {
                    Text[] fragments = nameHighlight.fragments();
                    String highlightedName = "";
                    for (Text fragment : fragments) {
                        highlightedName += fragment.string();
                    }
                    item.setName(highlightedName);
                }

                    items.add(item);
                }
                 return new PageDTO<>(total, items);
            }
        } catch (IOException e) {
            log.error("查询失败");
            e.printStackTrace();
        }

        return null;
    }
}
